package com.mgy.example.utils;

import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * java AES加密和c# AES加密互转
 */
public class AESUtil {
    /**
     * java  AES加密
     *
     * @param data     需要加密的内容
     * @param password 加密密钥
     * @return
     */
    public static String encrypt(String data, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        java.security.SecureRandom random = java.security.SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();

        //如下代码是标准的AES加密处理，C#可以实现
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = data.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        BASE64Encoder base64Decoder = new BASE64Encoder();
        return base64Decoder.encode(cipher.doFinal(byteContent));
    }


    /**
     * java的key转换为c#的key
     *
     * @param key
     * @return
     */
    public static String javaKeyToCSharpKey(String key) throws NoSuchAlgorithmException {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        java.security.SecureRandom random = java.security.SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        BASE64Encoder coder = new BASE64Encoder();

        return coder.encode(enCodeFormat);
    }


    /**
     * 以下方法为C#解密java用AES加密的数据
    /// <summary>
    /// 解密java的aes加密数据
    /// </summary>
    /// <param name="data">java的aes加密数据</param>
    /// <param name="key">java转换后的key</param>
    /// <returns></returns>
    public static string Decrypt(string data, string key)
    {
        byte[] keyArray = Convert.FromBase64String(key);
        byte[] toEncryptArray = Convert.FromBase64String(data);
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        //必须设置为ECB
        rDel.Mode = CipherMode.ECB;
        //必须设置为PKCS7
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    */
}
